package dao

import (
	"fmt"
	"haiqiu-go-admin/entity"
	"haiqiu-go-admin/entity/dto"
	"haiqiu-go-admin/utils"
	"log"
	"strconv"
)

// PostById 根据ID查询数据
func PostById(id int64) (*entity.SysPosition, error) {
	row := DB.QueryRow("select * from sys_position where id = ?", id)
	var sysPosition entity.SysPosition
	err := row.Scan(
		&sysPosition.Id,
		&sysPosition.PositionCode,
		&sysPosition.PositionName,
		&sysPosition.Describe,
		&sysPosition.Sort,
		&sysPosition.Icon,
		&sysPosition.Status,
		&sysPosition.CreateTime,
		&sysPosition.UpdateTime,
	)
	if err != nil {
		panic(err)
	}
	return &sysPosition, nil
}

// PostPageCount 分页查询总条数
func PostPageCount(positionQueryDto dto.PositionQueryDto) (count int64) {
	wrapper := utils.QueryWrapper().Count("sys_position")
	getPostCondition(positionQueryDto, wrapper)
	err := DB.QueryRow(wrapper.GetSql(), wrapper.GetVal()...).Scan(&count)
	if err != nil {
		log.Println(err.Error())
	}
	return count
}

func getPostCondition(positionQueryDto dto.PositionQueryDto, wrapper *utils.Wrapper) {
	if positionQueryDto.Params.PositionCode != nil {
		wrapper.Like("position_code", *positionQueryDto.Params.PositionCode)
	}
	if positionQueryDto.Params.PositionName != nil {
		wrapper.Like("position_name", *positionQueryDto.Params.PositionName)
	}
	if positionQueryDto.Params.Status != nil {
		wrapper.Eq("status", *positionQueryDto.Params.Status)
	}
}

// PostPageList 分页查询数据
func PostPageList(positionQueryDto dto.PositionQueryDto) (*[]entity.SysPosition, error) {
	wrapper := utils.QueryWrapper().Page("sys_position", positionQueryDto.PageIndex, positionQueryDto.PageSize)
	getPostCondition(positionQueryDto, wrapper)
	rows, err := DB.Query(wrapper.GetSql(), wrapper.GetVal()...)
	if err != nil {
		log.Println(err.Error())
		return nil, err
	}
	sysPosts := make([]entity.SysPosition, 0)
	for rows.Next() {
		var sysPost = entity.SysPosition{}
		err := rows.Scan(
			&sysPost.Id,
			&sysPost.PositionCode,
			&sysPost.PositionName,
			&sysPost.Describe,
			&sysPost.Sort,
			&sysPost.Icon,
			&sysPost.Status,
			&sysPost.CreateTime,
			&sysPost.UpdateTime,
		)
		if err != nil {
			log.Println(err.Error())
			return nil, err
		}
		sysPosts = append(sysPosts, sysPost)
	}
	return &sysPosts, nil
}

// PostAdd 新增数据
func PostAdd(sysPost *entity.SysPosition) (int64, error) {
	exec, err := DB.Exec("INSERT INTO `sys_position` "+
		"(`id`, `position_code`, `position_name`, `describe`, `sort`, `icon`, `status`, "+
		"`create_time`, `update_time`) VALUES "+
		"(?,?,?,?,?,?,?,?,?);",
		&sysPost.Id,
		&sysPost.PositionCode,
		&sysPost.PositionName,
		&sysPost.Describe,
		&sysPost.Sort,
		&sysPost.Icon,
		&sysPost.Status,
		&sysPost.CreateTime,
		&sysPost.UpdateTime,
	)
	if err != nil {
		return 0, err
	}
	rowsAffected, err := exec.RowsAffected()
	if err != nil {
		return 0, err
	}
	return rowsAffected, nil
}

// PostUpdate 根据ID更新数据
func PostUpdate(sysPost *entity.SysPosition) (int64, error) {
	exec, err := DB.Exec("UPDATE `sys_position` set "+
		"position_code = ?,position_name=?,`describe`=?,`sort`=?,icon=?,"+
		"`status`=?,create_time=?,update_time=? where id = ?",
		&sysPost.PositionCode,
		&sysPost.PositionName,
		&sysPost.Describe,
		&sysPost.Sort,
		&sysPost.Icon,
		&sysPost.Status,
		&sysPost.CreateTime,
		&sysPost.UpdateTime,
		&sysPost.Id,
	)
	if err != nil {
		return 0, err
	}
	rowsAffected, err := exec.RowsAffected()
	if err != nil {
		return 0, err
	}
	return rowsAffected, nil
}

// PostDelete 根据ID删除数据
func PostDelete(id int64) (int64, error) {
	exec, err := DB.Exec("delete from sys_position where id = ?")
	if err != nil {
		panic(err)
		return 0, err
	}
	rowsAffected, err := exec.RowsAffected()
	if err != nil {
		panic(err)
		return 0, err
	}
	return rowsAffected, nil
}

// PostDeleteBatch 根据ID批量删除数据
func PostDeleteBatch(ids []int64) (int64, error) {
	var idsStr string
	for index, id := range ids {
		if index == len(ids)-1 {
			idsStr += strconv.FormatInt(id, 10)
		} else {
			idsStr += strconv.FormatInt(id, 10) + ", "
		}
	}
	exec, err := DB.Exec("delete from sys_position where id in (?)", idsStr)
	if err != nil {
		panic(err)
		return 0, err
	}
	rowsAffected, err := exec.RowsAffected()
	if err != nil {
		panic(err)
		return 0, err
	}
	return rowsAffected, nil
}

// PostList 查询所有数据
func PostList() (*[]entity.SysPosition, error) {
	rows, err := DB.Query("select * from sys_position")
	if err != nil {
		panic(err)
		return nil, err
	}
	var sysPosts []entity.SysPosition
	for rows.Next() {
		var sysPost entity.SysPosition
		err := rows.Scan(
			&sysPost.Id,
			&sysPost.PositionCode,
			&sysPost.PositionName,
			&sysPost.Describe,
			&sysPost.Sort,
			&sysPost.Icon,
			&sysPost.Status,
			&sysPost.CreateTime,
			&sysPost.UpdateTime,
		)
		if err != nil {
			panic(err)
			return nil, err
		}
		sysPosts = append(sysPosts, sysPost)
	}
	return &sysPosts, nil
}

func DeleteUserByPosition(userId int64) error {
	_, err := DB.Exec("delete from sys_user_position where user_id in (?)", userId)
	if err != nil {
		panic(err)
		return err
	}
	return nil
}

func AddUserByPosition(userId int64, roleIds []int64) error {
	var sqlStr string
	for _, postId := range roleIds {
		userId := strconv.FormatInt(userId, 10)
		postId := strconv.FormatInt(postId, 10)
		insertSql := fmt.Sprintf("insert into sys_user_position (user_id,position_id) values (%s,%s); ", userId, postId)
		sqlStr += insertSql
	}
	_, err := DB.Exec(sqlStr)
	if err != nil {
		return err
	}
	return nil
}

func PositionByUserId(userId int64) (*[]entity.SysPosition, error) {
	rows, err := DB.Query("SELECT sp.* FROM `sys_user_position` sup "+
		"INNER JOIN sys_position sp on sp.id = sup.position_id "+
		"WHERE sup.user_id = ?", userId)
	if err != nil {
		return nil, err
	}
	var sysPosts []entity.SysPosition
	for rows.Next() {
		var sysPost entity.SysPosition
		err := rows.Scan(
			&sysPost.Id,
			&sysPost.PositionCode,
			&sysPost.PositionName,
			&sysPost.Describe,
			&sysPost.Sort,
			&sysPost.Icon,
			&sysPost.Status,
			&sysPost.CreateTime,
			&sysPost.UpdateTime,
		)
		if err != nil {
			panic(err)
			return nil, err
		}
		sysPosts = append(sysPosts, sysPost)
	}
	return &sysPosts, nil
}
